package org.jetlinks.pro.assets.impl.terms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.web.authorization.Dimension;
import org.jetlinks.pro.assets.DimensionInfo;
import org.jetlinks.pro.assets.impl.entity.DimensionAssetBindingEntity;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 根据资产查询维度条件.比如查询 和设备A关联的机构信息
 * <pre>
 * {
 * "column":"id", //维度主键列名
 * "termType": "assets-dim",//固定
 * "value":{
 *      "assetType":"device",//资产类型
 *      "assetIds":["device1","device2"],资产ID
 *      "dimensionType":"org",//维度类型
 *      "relations":["owner"] //关系
 *      }
 * }
 * </pre>
 *
 * @author zhouhao
 * @since 1.11
 */
@Getter
@Setter
public class AssetsDimensionTerm {

    private List<String> assetIds;

    private String dimensionType;

    private String assetType;

    private boolean not;

    private List<String> relations;

    public AssetsDimensionTerm not(boolean not) {
        this.not = not;
        return this;
    }

    public AssetsDimensionTerm relation(String relation) {
        if (relations == null) {
            relations = new ArrayList<>();
        }
        relations.add(relation);
        return this;
    }


    public static AssetsDimensionTerm of(String assetType, String dimensionType, List<String> assetIds) {
        AssetsDimensionTerm term = new AssetsDimensionTerm();
        term.setAssetIds(assetIds);
        term.setDimensionType(dimensionType);
        term.setAssetType(assetType);
        return term;
    }

    public static AssetsDimensionTerm of(Term term) {
        Object value = term.getValue();
        if (value instanceof AssetsDimensionTerm) {
            return ((AssetsDimensionTerm) value);
        }
        JSONObject obj;
        if (value instanceof String) {
            obj = JSON.parseObject(String.valueOf(value));
        } else if (value instanceof Map) {
            obj = new JSONObject(((Map) value));
        } else {
            throw new UnsupportedOperationException("error.unsupported_term");
        }
        AssetsDimensionTerm assetsTerm = obj.toJavaObject(AssetsDimensionTerm.class).validate();
        assetsTerm.setNot(term.getOptions().contains("not"));
        return assetsTerm;
    }

    public AssetsDimensionTerm validate() {
        Assert.hasText(assetType, "validation.type_can_not_be_empty");
        return this;
    }

}
